package com.ouman.luoliluoli;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.icu.util.Calendar;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.ouman.luoliluoli.models.UserInfo;
import com.ouman.luoliluoli.utils.MultipartUtility;
import com.ouman.luoliluoli.utils.GlobalConstants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.app.Activity.RESULT_CANCELED;


public class RegisterFragment extends Fragment {
    private OnFragmentInteractionListener mListener;

    private CardView cardViewAvatar;
    private ImageView avatar;
    private String gender = "default";
    private String birthdayDate;
    private Calendar calendar;
    private RadioGroup radioGender;
    private RadioButton radioMale;
    private RadioButton radioFemale;
    private RadioButton radioOther;


    private EditText userEmail;
    private EditText passWord;
    private EditText passWordConfirm;
    private EditText sign;
    private EditText userName;
    private EditText birthday;
    private Button cancelButton;
    private Button confirmButton;

    private ProgressDialog progressDialog;

    private File avatarImageFile;
    private GlobalConstants globalConstants;
    private static final int CAMERA_CODE = 1;
    private static final int GALLERY_CODE = 2;
    private static final int CROP_CODE = 3;

    private Boolean clickedAvatar = false;

    private UserInfo userInfo;

    private long nowTime;
    public RegisterFragment() {
        // Required empty public constructor
    }


    public static RegisterFragment newInstance(String param1, String param2) {
        RegisterFragment fragment = new RegisterFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_register, container, false);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("注册");

        //设置圆形头像
        cardViewAvatar = (CardView) view.findViewById(R.id.cardViewAvatar);
        avatar = (ImageView) view.findViewById(R.id.imageViewAvatar);
        radioGender = (RadioGroup) view.findViewById(R.id.radioGender);
        radioMale = (RadioButton) view.findViewById(R.id.radioButtonMale);
        radioFemale = (RadioButton) view.findViewById(R.id.radioButtonFemale);
        radioOther = (RadioButton) view.findViewById(R.id.radioButtonOther);

        userEmail = (EditText) view.findViewById(R.id.editTextUserEmail);
        passWord = (EditText) view.findViewById(R.id.editTextPassword);
        passWordConfirm = (EditText) view.findViewById(R.id.editTextPasswordConfirm);
        sign = (EditText) view.findViewById(R.id.editTextSign);
        userName = (EditText) view.findViewById(R.id.editTextUserName);
        birthday = (EditText) view.findViewById(R.id.editTextBirthday);
        cancelButton = (Button) view.findViewById(R.id.buttonCancel);
        confirmButton = (Button) view.findViewById(R.id.buttonConfirm);


        return view;
    }

    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);

        cardViewAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickedAvatar = true;
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, GALLERY_CODE);
            }
        });

        radioFemale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gender = radioFemale.getText().toString();
                System.out.println("Got gender: " + gender);
            }
        });

        radioMale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gender = radioMale.getText().toString();
                System.out.println("Got gender: " + gender);

            }
        });
        radioOther.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gender = radioOther.getText().toString();
                System.out.println("Got gender: " + gender);

            }
        });
        birthday.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b){
                    new DatePickerDialog(getActivity(),
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int month, int day) {
                                    // TODO Auto-generated method stub
                                    int mYear = year;
                                    int mMonth = month;
                                    int mDay = day;
                                    // 更新EditText控件日期 小于10加0
                                    birthday.setText(new StringBuilder()
                                            .append("生日: ")
                                            .append(mYear)
                                            .append("-")
                                            .append((mMonth + 1) < 10 ? "0"
                                                    + (mMonth + 1) : (mMonth + 1))
                                            .append("-")
                                            .append((mDay < 10) ? "0" + mDay : mDay));

                                    String[] birthS = birthday.getText().toString().split(" ");
                                    birthdayDate = birthS[birthS.length - 1];
                                    System.out.println("[IMPORTANT] birthday date string: " + birthdayDate);
                                    sign.requestFocus();
                                }
                            }, 1998, 2, 26).show();
                }else{
                    System.out.println("失去了焦点");
                }
            }
        });
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().getFragmentManager().beginTransaction().replace(R.id.fragment_container_login, new LoginFragment()).commit();
            }
        });

        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!userEmail.getText().toString().equals("") &&
                        !passWord.getText().toString().equals("") &&
                        !birthday.getText().toString().equals("") &&
                        !sign.getText().toString().equals("") &&
                        !userName.getText().toString().equals("")){
                    if (emailOrPhoneValid(userEmail.getText().toString())){
                        if (signValid(sign.getText().toString())){
                            if (passWordConfirm.getText().toString().equals(passWord.getText().toString())){
                                if (!gender.equals("default")){
                                    if (clickedAvatar){
                                        progressDialog = new ProgressDialog(getActivity());
                                        progressDialog.setCancelable(true);
                                        progressDialog.setMessage("作死的注册中...准备上天...");
                                        progressDialog.setCancelable(false);
                                        progressDialog.setIndeterminate(true);
                                        progressDialog.show();

                                        //开始准备上天！！
                                        globalConstants = new GlobalConstants();
                                        userInfo = new UserInfo();
                                        userInfo.setEmail(userEmail.getText().toString());
                                        userInfo.setGender(gender);
                                        userInfo.setPassWord(passWord.getText().toString());
                                        // 这个birthday有问题卧槽，不能包含除日期以外的字符串
                                        userInfo.setBirthday(birthdayDate);
                                        userInfo.setSign(sign.getText().toString());
                                        userInfo.setNickName(userName.getText().toString());

                                        //开启一个新线程，向服务器上传数据
                                        new Thread(){
                                            public void run(){
                                                // 注意啦！！！http的任何操作都必须要要在子线程中进行，android怕你
                                                // 阻塞线程！！
                                                try{
                                                    MultipartUtility multipart = new MultipartUtility(GlobalConstants.API_USER, "utf-8");
                                                    multipart.addHeaderField("User-Agent", "CodeJava");
                                                    multipart.addHeaderField("Test-Header", "Header-Value");

                                                    multipart.addFormField("user_birthday", userInfo.getBirthday());
                                                    multipart.addFormField("user_email", userInfo.getEmail());
                                                    multipart.addFormField("user_gender", userInfo.getGender());
                                                    multipart.addFormField("user_home", userInfo.getHome());
                                                    multipart.addFormField("user_location", userInfo.getLocation());
                                                    multipart.addFormField("user_major", userInfo.getMajor());
                                                    multipart.addFormField("user_name", userInfo.getNickName());
                                                    multipart.addFormField("user_password", userInfo.getPassWord());
                                                    multipart.addFormField("user_phone", userInfo.getPhone());
                                                    multipart.addFormField("user_QQ", userInfo.getQQ());
                                                    multipart.addFormField("user_relation", userInfo.getRelationStatus());
                                                    multipart.addFormField("user_school", userInfo.getSchool());
                                                    multipart.addFormField("user_wechat", userInfo.getWechat());
                                                    multipart.addFormField("user_sign", userInfo.getSign());

                                                    multipart.addFilePart("user_avatar", avatarImageFile);
                                                    String response = multipart.finish();

                                                    System.out.println("SERVER REPLIED:" + response);
                                                    // {"status": "info", "message": "user already exist", "data": {"user_id": 2}}
                                                    // {"status": "success", "message": "success upload picture to qi niu.", "data": {"user_id": 2}}
                                                    try{
                                                        JSONObject responseJson = new JSONObject(response);
                                                        String status = responseJson.getString("status");
                                                        System.out.println(status);
                                                        Message msg = Message.obtain();

                                                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                                                        SharedPreferences.Editor editor = preferences.edit();
                                                        if (status.equals("info")){
                                                            msg.what = 0;
                                                            String userId = responseJson.getJSONObject("data").getString("user_id");
                                                            editor.putString("userId", userId);
                                                            editor.apply();
                                                        } else if (status.equals("success")){
                                                            msg.what = 1;
                                                            String userId = responseJson.getJSONObject("data").getString("user_id");
                                                            editor.putString("userId", userId);
                                                            editor.apply();
                                                        } else if (status.equals("error")){
                                                            msg.what = 2;
                                                        }
                                                        // info会返回一个user_id
                                                        // success 也会返回一个user_id,这个必须存入本地
                                                        doPostHandler.sendMessage(msg);
                                                    } catch (JSONException e){
                                                        System.out.print(e);
                                                        Message msg = Message.obtain();
                                                        msg.what = 5;
                                                        doPostHandler.sendMessage(msg);
                                                    }

                                                }catch (IOException e){
                                                    Message msg = Message.obtain();
                                                    msg.what = 6;
                                                    doPostHandler.sendMessage(msg);
                                                    System.out.println(e);
                                                }
                                            }
                                        }.start();

                                    } else {
                                        Toast.makeText(getActivity(), "为了让您在萝莉萝莉光彩四溢，务必设置您的头像", Toast.LENGTH_SHORT).show();
                                    }
                               }else{
                                   Toast.makeText(getActivity(), "性别将无法更改，请再次确认性别", Toast.LENGTH_SHORT).show();
                               }
                            }else {
                                Toast.makeText(getActivity(), "两次密码输入不一致", Toast.LENGTH_SHORT).show();
                                passWordConfirm.setError("可以设置一个简单容易记的密码哟");
                            }
                        }else {
                            sign.setError("个性签名过于屌");
                            Toast.makeText(getActivity(), "个性签名过于屌", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        userEmail.setError("邮箱或者手机号格式不正确");
                        Toast.makeText(getActivity(), "邮箱或者手机号格式不正确, 手机号要是11位哟", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(getActivity(), "还有信息为填写哟", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private Handler doPostHandler = new Handler(){
        /* this method doing main thread things after post method */
        public void handleMessage(Message msg){
            if (msg.what == 0){
                // if 0, means info , user already exist
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "用户名已存在，请直接登陆", Toast.LENGTH_SHORT).show();
            }else if (msg.what == 1){
                // if 1 means success, got ahead
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "注册成功, 欢迎来到LuoliLuoli", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                getActivity().startActivity(intent);
                getActivity().finish();

                // 标记一下isLogin
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("isLogin", true);
                editor.apply();
            }else if (msg.what == 2){
                // this means error
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "出现了致命的错误，可能导致你的手机爆炸", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 5){
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "服务器错误，可能是上传的图片过大，请裁剪后上传", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 6){
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "慌了，服务器貌似出问题，用户爸爸们可以断网然后直接点击登录，你懂得，秘密入口", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @NonNull
    private Boolean signValid(String s){
        if (s.contains("习近平") || s.contains("屌") || s.contains("牛逼")){
            return false;
        }else {
            return true;
        }
    }

    @NonNull
    private Boolean emailOrPhoneValid(String s){
        // check an email or Phone valid or not
        if (isNumeric(s)){
            // 说明是数字的手机号
            System.out.println("手机号是: " + s);
            if (s.length() == 11){
                return true;
            }else{
                return false;
            }
        }else {
            if (s.contains("@")){
                return true;
            }else{
                return false;
            }
        }
    }

    public static boolean isNumeric(String str){
        for (int i = str.length();--i>=0;){
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }

    //调用系统相册选取重写这个方法
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case GALLERY_CODE:
                if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(getActivity(), "取消了从相册选择", Toast.LENGTH_LONG).show();
                    return;
                }

                try {
                    Uri imageUri = data.getData();
                    System.out.println(imageUri);
                    System.out.println("====!!!!!! uri---" + imageUri.getPath());
                    String realPath = getRealPathFromUri(getActivity(), imageUri);
                    System.out.println("====!!!!!! realpath----" + realPath);
//                    avatarImageFile = new File(realPath);
                    cropImage(imageUri);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case CROP_CODE:
                try {
                    if(data!=null) {
                        Bundle extras = data.getExtras();
                        Bitmap bm = extras.getParcelable("data");
                        avatar.setImageBitmap(bm);

                        Uri uri = getImageFile(bm);
                        //也可以直接将绝对路径转为文件
                        System.out.println("croped image url: " + uri);
                        System.out.println("try another path: " + uri.getPath());
                        String realPath = uri.getPath();
                        System.out.println("croped image real path: " + realPath);
                        avatarImageFile = new File(realPath);
                    }else {
                        Toast.makeText(getActivity(), "some error crop image", Toast.LENGTH_SHORT);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void cropImage(Uri uri){
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_CODE);
    }
    public Uri getImageFile(Bitmap bm) {
        byte[] bytes;
        ByteArrayOutputStream stream;
        String filePath;
        // 图片允许最大空间 单位：KB
        double maxSize = 100;
        stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
        bytes = stream.toByteArray();
        // 将字节换成KB
        double mid = bytes.length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            // 获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
            // 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
            // （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bm = zoomImage(bm, bm.getWidth() / Math.sqrt(i), bm.getHeight() / Math.sqrt(i));
            stream = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
            bytes = stream.toByteArray();
        }
        Uri uri = saveBitmap(bm);
        return uri;
    }
    public Uri saveBitmap(Bitmap bm) {
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/com.ouman.luoliluoli");//新建文件夹用来保存图片，地址自己写
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }//如果地址不存在，则新建
        if (nowTime == 0) {
            nowTime = System.currentTimeMillis();
        }//获取系统时间
        File img = new File(tmpDir.getAbsolutePath() + "/" + nowTime + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);//压缩文件
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        /* this method get real path from Uri*/
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
